package com.example.utils;

import com.example.common.CustomException;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Properties;

/**
 * ftp上传文件工具类
 *
 * @author czx
 * @since 2022/6/2 16:23
 */

@Component
@Slf4j
public class FtpUtil {

    /**
     * 存储路径
     */
    public static String rootPath;
    /**
     * 图片路径
     */
    private static String imgUrl;
    /**
     * ftp服务器IP
     */
    private static String host;
    /**
     * ftp服务器端口
     */
    private static int port;
    /**
     * 用户名
     */
    private static String userName;
    /**
     * 密码
     */
    private static String password;

    /**
     * 获取ssh连接
     *
     * @return 连接
     * @throws JSchException 连接异常
     */
    private static ChannelSftp getChannel() throws JSchException {
        JSch jSch = new JSch();
        // -> ssh root@host:port
        Session schSession = jSch.getSession(userName, host, port);
        schSession.setPassword(password);

        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        schSession.setConfig(sshConfig);
        schSession.connect();

        ChannelSftp sftp = (ChannelSftp) schSession.openChannel("sftp");
        sftp.connect();

        return sftp;
    }

    /**
     * 创建目录
     *
     * @param path 目录
     * @param sftp 上传下载
     * @throws SftpException 异常
     */
    private static void createDir(String path, ChannelSftp sftp) throws SftpException {
        String[] folders = path.split("/");
        sftp.cd("/");
        for (String folder : folders) {
            if (folder.length() > 0) {
                try {
                    sftp.cd(folder);
                } catch (SftpException e) {
                    sftp.mkdir(folder);
                    sftp.cd(folder);
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param inputStream 输入流
     * @param filePath    文件路径
     * @param name        文件名
     * @return 路径
     */
    public static String put(InputStream inputStream, String filePath, String name) {
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + "/" + filePath + "/";
            createDir(path, sftp);

            // 上传文件
            sftp.put(inputStream, path + name);
            log.info("{} 图片上传成功！", path + name);
            sftp.quit();
            sftp.exit();

        } catch (JSchException e) {
            log.error("上传失败:{}", e.getMessage());
            throw new CustomException("图片上传失败");
        } catch (SftpException e) {
            log.error("创建目录失败:{}", e.getMessage());
            throw new CustomException("创建目录失败");
        }
        // 处理返回的路径
        return imgUrl + filePath + "/" + name;
    }

    public static void delImages(String name) {
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + name;
            sftp.rm(path);
            log.info("{}删除成功", name);
            sftp.quit();
            sftp.exit();
        } catch (JSchException | SftpException e) {
            log.info("删除图片失败:{}", e.getMessage());
            throw new CustomException("删除图片失败");
        }
    }

    @Value("${ftp.rootPath}")
    public void setRootPath(String rootPath) {
        FtpUtil.rootPath = rootPath;
    }

    @Value("${ftp.host}")
    public void setHost(String host) {
        FtpUtil.host = host;
    }

    @Value("${ftp.img.url}")
    public void setImgUrl(String imgUrl) {
        FtpUtil.imgUrl = imgUrl;
    }

    @Value("${ftp.port}")
    public void setPort(int port) {
        FtpUtil.port = port;
    }

    @Value("${ftp.userName}")
    public void setUserName(String userName) {
        FtpUtil.userName = userName;
    }

    @Value("${ftp.password}")
    public void setPassword(String password) {
        FtpUtil.password = password;
    }
}
